import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
// 引入NProgress及其样式
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 路由配置
const routes = [
  {
    // 登录
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      hidden: true
    }
  },
  {
    // 主页
    path: '/',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '/user',
        component: () => import('@/views/user/user.vue'),
        meta: {
          title: '用户管理',
          icon: 'User',
          hidden: false
        }
      },
      {
        path: '/system',
        meta: {
          title: '系统管理',
          icon: 'Menu',
          hidden: false
        },
        children: [
          {
            path: '/system/account',
            component: () => import('@/views/system/account.vue'),
            meta: {
              title: '账号管理',
              icon: 'Avatar',
              hidden: false
            }
          },
          {
            path: '/system/dictionary',
            component: () => import('@/views/system/dictionary.vue'),
            meta: {
              title: '字典管理',
              icon: 'Collection',
              hidden: false
            }
          },
          {
            path: '/system/dictionary-detail/:typeKey',
            component: () => import('@/views/system/dictionary-detail.vue'),
            meta: {
              title: '字典详情',
              icon: 'Collection',
              hidden: true
            }
          },
          {
            path: '/system/parameter',
            component: () => import('@/views/system/parameter.vue'),
            meta: {
              title: '参数管理',
              icon: 'Setting',
              hidden: false
            }
          }
        ]
      }
    ]
  },
  {
    // 404
    path: '/:pathMatch(.*)*',
    component: () => import('@/views/error/404.vue'),
    meta: {
      hidden: true
    }
  },
  {
    // 401
    path: '/401',
    component: () => import('@/views/error/401.vue'),
    meta: {
      hidden: true
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 白名单
const whiteList = ['/login','/404']

// 可选：自定义NProgress配置
NProgress.configure({ showSpinner: false })

// 全局路由守卫
router.beforeEach((to, from, next) => {
  NProgress.start() // 开始进度条
  const userStore = useUserStore()
  if(userStore.token){
    if (to.path === '/login') {
      next('/user')
    } else {
      next()
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      if (whiteList.includes(to.path)) {
        next()
      } else {
        next(`/login?redirectUrl=${to.path}`)
      }
    }
  }
})

// 路由跳转结束后关闭进度条
router.afterEach(() => {
  NProgress.done()
})

export default router